<template>
  <view>
		<up-navbar title="文件管理" :autoBack="true" placeholder></up-navbar>
		
    <view class="container">
      <image mode="widthFix" :src="`/static/fileType_big/${setIcon(icon)}_b.png`"></image>
      <text class="name" :title="fileName">{{ truncateMiddle(fileName) }}</text>
      <text class="memo">
        {{type == 'dir' ? '手机端暂时无法查看下载文件夹，请到电脑查看' : '暂时无法预览该文件，请下载后用其他应用打开'}}
      </text>
      <up-button v-if="type != 'dir'" @click="downloadClick" class="btn" type="primary" color="#027FFF" :text="`下载 (${fileSize})`"></up-button>
    </view>
  </view>
</template>

<script>
import { fileTypeFormat } from '@/utils/chat.js'
import { mapStores } from 'pinia'
import { chatApi, chatFileApi } from '@/apis/cloud/chat'
import download from '@/utils/download.js'

export default {
  name: "PreviewDoc",
  props: {

  },
  data () {
    return {
      url: '',
      fileName: '',
      fileSize: '',
      icon: '',
      nc_id: '',
      systemInfo: '',
      fid: '',
      type: '',
    }
  },
  onLoad (options) {
    this.fileName = options.fileName;
    this.url = options.url;
    this.fid = options.fid;
		this.type = options.type;
    this.fileSize = options.fileSize;
		this.nc_id = options.nc_id ? options.nc_id : '';
  },
	created() {
		this.systemInfo = uni.getSystemInfoSync();
	},
  methods: {
		async shareFile(fileUrl, fileName = '') {
		    if (!fileUrl) {
					return uni.showToast({ title: '文件链接错误', icon: 'none' });
		    }
		
		    // 自动获取文件名
		    if (!fileName) {
					fileName = fileUrl.split('/').pop().split('?')[0] || 'file';
		    }
		
		    // 检测是否微信浏览器
		    const ua = navigator.userAgent.toLowerCase();
		    const isWeChat = ua.includes('micromessenger');
		
		    if (isWeChat) {
					uni.showModal({
						title: '提示',
						content: '请在浏览器中打开此页面后再分享文件',
						showCancel: false
					});
					return;
		    }

				// H5：安卓浏览器支持文件分享
				// =============================
		    // #ifdef H5
		    if (navigator.share && navigator.canShare) {
					try {
						
						const params = {
							url: `index.php/users/files/${this.fid}/get-stream`
						}
						const msg = await chatFileApi(this.userInfo?.token, params);

						const file = new File([msg], fileName, { type: 'application/octet-stream' });
						
						if (navigator.canShare && navigator.canShare({ files: [file] })) {
							await navigator.share({ files: [file], title: '分享文件', text: '请查收文件' });
							uni.hideLoading();
						} else {
							uni.hideLoading();
							alert('不支持分享文件');
						}
					} catch (e) {
						console.error(e);
						uni.hideLoading();
						uni.showToast({ title: '分享失败', icon: 'none' });
					}
					return;
		    }
		
		    // 不支持 share API
		    uni.showToast({ title: '当前浏览器不支持文件分享', icon: 'none' });
		    // #endif
		},
    truncateMiddle (text, maxLength = 20) {
      if (text.length <= maxLength) return text;
      const half = Math.floor(maxLength / 2);
      return `${text.slice(0, half)}...${text.slice(-half)}`;
    },
    setIcon () {
      const str = this.fileName.split('.');
      if(str.length == 1) {
      	return 'folder'
      }else {
      	return fileTypeFormat(str[str.length - 1])
      }
    },
    // 下载文件
    async downloadClick() {
			uni.showLoading({ title: '正在获取文件...', mask: true });
			console.log(this.systemInfo)
			if(this.systemInfo.platform == 'ios' || this.systemInfo.osName == 'ios') {
				this.shareFile(this.url.replace('http:', 'https:').replace(':81', ':88'), this.fileName)
				return
			}

      try {
        // uni.showLoading({ title: '正在下载', mask: true });
				
				const params = {
					url: `index.php/users/files/${this.fid}/temp`
				}
				const msg = await chatApi(this.userInfo?.token, params);

				let fileUrl = '';
        if(msg.code == 200) {
					fileUrl = msg.https;
				}else {
					uni.hideLoading();
					uni.showToast({
						icon: "none",
						title: '下载失败，请稍后重试'
					})
					return
				}
				uni.downloadFile({
					url: fileUrl,
					success: (res) => {
						plus.runtime.openFile(res.tempFilePath, {}, (err) => {
							console.log('openfile fail', err)
						});
						uni.hideLoading();
					},
					fail(err) {
						uni.hideLoading();
						console.log('获取失败:', err);
					}
				});
				

		//     const savePath = "file://storage/emulated/0/GreenCloud/" + this.fileName;

		//     // #ifdef APP-PLUS
		//     // 创建下载任务
		//     const dtask = plus.downloader.createDownload(fileUrl, {
		//       filename: savePath
		//     }, (downloadedFile, status) => {
		//       if (status === 200) {
		//         // 下载成功
		//         uni.showToast({
		//           title: '已保存到文件夹：/GreenCloud/' + fileName,
		//           icon: 'none',
		//           duration: 3000,
		//         });
		//         // 打开文件
		// 				setTimeout(() => {
		// 					uni.hideLoading();
		// 					plus.runtime.openFile(downloadedFile.filename, {}, (err) => {
		// 						console.log('openfile fail', err)
		// 					});
		// 				}, 800);
		//       } else {
		//         // 下载失败
		// 				uni.hideLoading();
		//         plus.downloader.clear(); // 清除任务
		//         uni.showToast({
		//           title: '下载失败，请稍后重试',
		//           icon: 'none'
		//         });
		//       }
		//     });
		
		// 		dtask.start(); // 开始下载
			//	// #endif
    
        // uni.hideLoading();
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          title: e.message || '下载失败',
          icon: 'error',
          duration: 2000
        });
      }
    },
		

  },
}
</script>

<style scoped lang="scss">
page {
  overflow: hidden;
  width: 100vw;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  image {
    width: 80px;
    margin-top: 170px;
    margin-bottom: 24px;
  }

  .name {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 2px;
  }

  .memo {
    margin-bottom: 18px;
    color: #999;
    font-size: 14px;
  }

  .btn {
    width: 30%;
  }
}

.download {
  position: fixed;
  bottom: 0;
  height: 80px;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #F2F3F4;

  image {
    width: 22px;
    height: 22px;
    margin-right: 4px;
  }
}
</style>
